package com.nut.spp.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.fasterxml.jackson.databind.JsonNode;
import com.nut.spp.api.req.ShopCheckReq;
import com.nut.spp.api.req.ShopQueryReq;
import com.nut.spp.common.Result;
import com.nut.spp.entity.*;
import com.nut.spp.enums.IdTagEnum;
import com.nut.spp.enums.ShopStatusEnum;
import com.nut.spp.jbb.JbbService;
import com.nut.spp.jbb.req.CorpReq;
import com.nut.spp.mapper.*;
import com.nut.spp.service.ShopService;
import com.nut.spp.util.DateUtil;
import com.nut.spp.util.IdUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.Objects;
import java.util.Set;

@Service
@Slf4j
public class ShopServiceImpl implements ShopService {

    @Autowired
    private MemberMapper memberMapper;

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private ShopDetailMapper shopDetailMapper;

    @Autowired
    private ShopCheckRecordMapper shopCheckRecordMapper;

    @Autowired
    private JbbService jbbService;

    @Autowired
    private JbbCorpCreateMapper jbbCorpCreateMapper;

    @Override
    public Result<IPage<Shop>> listPage(ShopQueryReq req) {
        IPage<Shop> list = shopMapper.listPage(req.newPage(), req.getLon(), req.getLat(),
                req.getDistance(), req.getCatId(), req.getName(), req.getStatus());
        return Result.ok(list);
    }

    @Override
    public Result<Shop> getById(Serializable id) {

        if (id == null) {
            return Result.fail("当前还没有店铺");
        }

        Shop shop = shopMapper.selectById(id);
        if (shop == null) {
            return Result.ok();
        }

        ShopDetail detail = shopDetailMapper.selectById(id);
        detail.filled(shop);

        Long memberId = shop.getMemberId();
        Member member = memberMapper.selectById(memberId);

        return Result.ok(shop);
    }

    @Override
    public Result<Integer> add(Shop shop) {

        Long memberId = shop.getMemberId();
        if (memberId != null) {
            Shop one = shopMapper.selectByMemberId(memberId);
            if (one != null) {
                return Result.fail("该会员已有店铺");
            }
        }
        shop.setStatus(ShopStatusEnum.INIT.getValue());

        shopMapper.insert(shop);

        ShopDetail shopDetail = shop.getShopDetail();
        shopDetailMapper.insert(shopDetail);

        if (memberId != null) {
            Member update = new Member();
            update.setId(memberId);
            memberMapper.updateById(update);
        }

        return Result.ok(shop.getId());
    }

    @Override
    public Result updateById(Shop shop) {

        //memberId 不更新
        shop.setMemberId(null);

        if (shop.needUpdate()) {
            shopMapper.updateById(shop);
        }

        if (shop.needUpdateDetail()) {
            ShopDetail detail = shop.getShopDetail();
            shopDetailMapper.updateById(detail);
        }

        return Result.ok();
    }

    @Override
    public Result deleteByIds(Set<Integer> ids) {
        for (Integer id : ids) {
            shopMapper.deleteById(id);
        }
        return Result.ok();
    }

    @Override
    public Result<Shop> getByMemberId(Long memberId, Integer shopId) {

        if (shopId != null) {
            return this.getById(shopId);
        }

        Shop shop = shopMapper.selectByMemberId(memberId);
        if (shop == null) {
            return Result.ok();
        }

        ShopDetail detail = shopDetailMapper.selectById(shop.getId());
        detail.filled(shop);

        return Result.ok(shop);
    }

    @Override
    public Result submit(Integer id) {

        Shop shop = shopMapper.selectById(id);
        ShopDetail detail = shopDetailMapper.selectById(id);
        detail.filled(shop);

        if (shop.getCompanyName() == null ||
                shop.getCompanyAddress() == null ||
                shop.getCompanyPath() == null ||
                shop.getLinkName() == null ||
                shop.getLinkPhone() == null ||
                shop.getLicenceNum() == null ||
                shop.getLicenceImg() == null ||
                shop.getLicenceScope() == null ||
                shop.getLicenceEndDate() == null ||
                shop.getLegalName() == null ||
                shop.getLegalIdent() == null ||
                shop.getLegalEndTime() == null ||
                shop.getLegalMobile() == null ||
                shop.getLegalIdentFront() == null ||
                shop.getLegalIdentBack() == null ||
                shop.getBankAccountName() == null ||
                shop.getBankName() == null ||
                shop.getBankBranchName() == null ||
                shop.getBankAccountNum() == null ||
                shop.getBankNo() == null ||
                shop.getCompanyPathNo() == null ||
                shop.getBankOpen() == null) {
            return Result.fail("请将资料补全");
        }

        Shop update = new Shop();
        update.setId(id);
        update.setSubmitTime(DateUtil.getNowDateTime());
        update.setStatus(ShopStatusEnum.PAY_SUBMITTED.getValue());
        shopMapper.updateById(update);

        //提交 汇付审核 开企业账号

        submitCorpCreate(shop);

        return Result.ok();
    }

    @Override
    public Result queryCheckStatus(Integer id) {

        Shop shop = shopMapper.selectById(id);
        if (shop == null) {
            return Result.ok();
        }

        Shop shop1 = new Shop();
        shop1.setId(id);
        shop1.setStatus(shop.getStatus());
        shop1.setReason(shop.getReason());

        return Result.ok(shop1);
    }

    private void submitCorpCreate(Shop shop) {

        CorpReq req = new CorpReq();
        req.setAddress(shop.getAddress());
        req.setBankCardNo(shop.getBankAccountNum());
        req.setBankLicenseUrl(shop.getBankOpen());
        req.setBankNo(shop.getBankNo());

//        Long orderId = IdUtil.generatedCommonId(IdTagEnum.corpCreate);
//        req.setBizNo(orderId.toString());

        String companyPathNo = shop.getCompanyPathNo();
        String[] split = companyPathNo.split(",");
        req.setProvinceCode(split[0]);
        req.setCityCode(split[1]);
        req.setIdCardBackUrl(shop.getLegalIdentBack());
        req.setIdCardFrontUrl(shop.getLegalIdentFront());
        req.setLegalCertId(shop.getLegalIdent());
        req.setLegalCertIdExpires(shop.getLegalEndTime().replace("-", ""));
        req.setLegalMp(shop.getLegalMobile());
        req.setLegalPerson(shop.getLegalName());
        req.setLicenseUrl(shop.getLicenceImg());

        req.setRealName(shop.getCompanyName());
        req.setScope(shop.getLicenceScope());
        req.setSocialCreditCode(shop.getLicenceNum());
        req.setSocialCreditCodeExpires(shop.getLicenceEndDate().replace("-", ""));

        String ss = jbbService.corpCreate(req);

        JbbCorpCreate corpCreate = new JbbCorpCreate();
        corpCreate.setShopId(shop.getId());
//        corpCreate.setOrderId(orderId.toString());
        jbbCorpCreateMapper.insert(corpCreate);

    }

    @Override
    public Result check(ShopCheckReq req) {

        Integer shopId = req.getShopId();

        Shop shop = shopMapper.selectById(shopId);

        Integer status = shop.getStatus();

        if (!Objects.equals(status, ShopStatusEnum.PAY_PASS.getValue())) {
            return Result.fail("支付审核通过，才可以审核");
        }

        Shop update = new Shop();
        update.setId(req.getShopId());
        update.setStatus(req.getAction() == 1 ?
                ShopStatusEnum.CHECK_PASS.getValue() :
                ShopStatusEnum.CHECK_FAIL.getValue());

        shopMapper.updateById(update);

        ShopCheckRecord record = new ShopCheckRecord();
        record.setShopId(req.getShopId());
        record.setUserId(req.getUserId());
        record.setUserName(req.getUserName());
        record.setAction(req.getAction());
        record.setRemark(req.getReason());
        shopCheckRecordMapper.insert(record);

        return Result.ok();
    }

    @Override
    public Result jbbCorpCreate(JsonNode obj) {

        String bizNo = obj.get("bizNo").asText();
        String settleAccountId = obj.get("settleAccountId").asText();
        String status = obj.get("status").asText();

        String auditDesc = null;
        if (obj.get("auditDesc") != null) {
            auditDesc = obj.get("auditDesc").asText();
        }

        JbbCorpCreate corpCreate = jbbCorpCreateMapper.selectByOrderId(bizNo);
        if (corpCreate == null) {
            return Result.fail("找不到记录,bizNo=" + bizNo);
        }

        Integer shopId = corpCreate.getShopId();

        Shop shop = shopMapper.selectById(shopId);
        if (shop == null) {
            return Result.fail("找不到店铺,shopId=" + shopId);
        }
        if (!shop.getStatus().equals(ShopStatusEnum.PAY_SUBMITTED.getValue())) {
            log.info("bizNo=" + bizNo + ",业务已处理");
            return Result.ok();
        }

        Shop update = new Shop();
        update.setId(shopId);
        update.setSettleAccountId(settleAccountId);

        //SUCCEEDED/FAILED
        Integer action = 0;
        if (status.equalsIgnoreCase("SUCCEEDED")) {
            action = 1;
            update.setStatus(ShopStatusEnum.PAY_PASS.getValue());
        } else {
            update.setStatus(ShopStatusEnum.PAY_FAIL.getValue());
        }
        update.setReason(auditDesc);
        shopMapper.updateById(update);

        ShopCheckRecord record = new ShopCheckRecord();
        record.setShopId(shopId);
        record.setUserId(0);
        record.setUserName("紧帮帮");
        record.setAction(action);
        record.setRemark(auditDesc);
        shopCheckRecordMapper.insert(record);

        return Result.ok();
    }

    @Override
    public Result authCircle(Shop req) {

        Integer id = req.getId();

        Shop shop = shopMapper.selectById(id);
        if (shop == null) {
            return Result.fail("找不到店铺");
        }

        Shop update = new Shop();
        update.setId(id);
        update.setCircle(req.getCircle());
        shopMapper.updateById(update);

        return Result.ok();
    }

}